package com.sskj.trafficcontrol.util;

import com.alibaba.fastjson.JSONObject;

import com.google.common.collect.Lists;
import com.sskj.trafficcontrol.model.pojo.TcCitys;
import com.sskj.trafficcontrol.model.pojo.TcControlCitys;
import com.sskj.trafficcontrol.model.vo.*;
import com.sskj.trafficcontrol.service.TrafficControlService;
import org.apache.poi.util.Beta;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;


/**
 * Created by qcl on 2018/9/11.
 * 微信小程序推送服务，
 * 包含获取access_token的服务
 */
@Service
@Slf4j
public class WxPushServiceQcl {

    @Autowired
    private TrafficControlService trafficControlService;

    @Autowired


    public static boolean isNumeric(String str){
        for (int i = str.length();--i>=0;){
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }

    /*
     * 微信小程序推送单个用户
     * */
    public  String pushOneUser(String noticeCity,String openid, String formid,Integer noticeType,String userCarNumber) {
        RestTemplate restTemplate = new RestTemplate();

        //获取access_token
        String access_token = getAccess_token(getOpenIdutil.appid, getOpenIdutil.secret);
        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send" +
                "?access_token=" + access_token;

        TcCitys tcCitys = trafficControlService.findByCityName(noticeCity);
        LuBangXianingInfoVO xianxing = null;
        TrafficControlBeanVO trafficControlBeanVO = new TrafficControlBeanVO();
        if(tcCitys!=null){
            //获取第三方的数据
            xianxing = LuBangXianxingUtil.getCityXianxingInfo(tcCitys.getCity());
            if(xianxing!=null){

                List<String> todayLocalXxWeihao = new ArrayList<>();
                List<String> nextdayLocalXxWeihao = new ArrayList<>();
                List<String> afterTomorrowLocalXxWeihao = new ArrayList<>();


                List<String> todayforeignXxWeihao = new ArrayList<>();
                List<String> nextforeignXxWeihao = new ArrayList<>();
                List<String> afterTomorrowforeignXxWeihao = new ArrayList<>();

                List<String> todayAllcarXxWeihao = new ArrayList<>();
                List<String> nextAllcarXxWeihao = new ArrayList<>();
                List<String> afterTomorrowAllcarXxWeihao = new ArrayList<>();

                if(xianxing.getLocalcar().size()!=0){
                    LuBangXianingInfoVO.LocalcarBean localcarBean = xianxing.getLocalcar().get(0);
                    todayLocalXxWeihao = getXxWeihao(localcarBean.getNumber(),0);  //今天
                    trafficControlBeanVO.setLocalRemarks(localcarBean.getSummary());
                }

                if(xianxing.getForeigncar().size()!=0){
                    LuBangXianingInfoVO.ForeigncarBean foreigncarBean = xianxing.getForeigncar().get(0);
                    todayforeignXxWeihao = getXxWeihao(foreigncarBean.getNumber(),0);//今天
                    trafficControlBeanVO.setForeignRemarks(foreigncarBean.getSummary());
                }
                //所有车辆
                if(xianxing.getAllcars().size()!=0){
                    LuBangXianingInfoVO.AllCarBean allCarBean = xianxing.getAllcars(). get(0);
                    todayAllcarXxWeihao = getXxWeihao(allCarBean.getNumber(),0);
                    trafficControlBeanVO.setAllCarRemarks(allCarBean.getSummary());
                }

                //封装限行规则
                trafficControlBeanVO.setTodayLocalXxWeihao(todayLocalXxWeihao);
                trafficControlBeanVO.setNextdayLocalXxWeihao(nextdayLocalXxWeihao);
                trafficControlBeanVO.setAfterTomorrowLocalXxWeihao(afterTomorrowLocalXxWeihao);

                trafficControlBeanVO.setTodayforeignXxWeihao(todayforeignXxWeihao);
                trafficControlBeanVO.setNextforeignXxWeihao(nextforeignXxWeihao);
                trafficControlBeanVO.setAfterTomorrowforeignXxWeihao(afterTomorrowforeignXxWeihao);

                trafficControlBeanVO.setTodayAllcarXxWeihao(todayAllcarXxWeihao);
                trafficControlBeanVO.setNextAllcarXxWeihao(nextAllcarXxWeihao);
                trafficControlBeanVO.setAfterTomorrowAllcarXxWeihao(afterTomorrowAllcarXxWeihao);
        }
    }

//拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户openid
        wxMssVo.setTemplate_id(getOpenIdutil.template_id);
        wxMssVo.setForm_id(formid);//formid


        Map<String, TemplateData> m = new HashMap<>(5);

        //城市
        TemplateData keyword1 = new TemplateData();
        keyword1.setValue(noticeCity);
        m.put("keyword1", keyword1);

        //限行号码
        StringBuffer stringBuffer = new StringBuffer();
        List<String> todayLocalXxWeihao = trafficControlBeanVO.getTodayLocalXxWeihao();
        List<String> todayforeignXxWeihao = trafficControlBeanVO.getTodayforeignXxWeihao();
        List<String> todayAllcarXxWeihao = trafficControlBeanVO.getTodayAllcarXxWeihao();

        stringBuffer.append("本地车限号："+getMsgInfo(todayLocalXxWeihao)+" ");
        stringBuffer.append("外地车限号："+getMsgInfo(todayforeignXxWeihao)+" ");
        stringBuffer.append("全部车限号："+getMsgInfo(todayAllcarXxWeihao));

        TemplateData keyword2 = new TemplateData();
        String value = stringBuffer.toString();
        if(stringBuffer.toString().length()>50){
            value = stringBuffer.toString().substring(0,50)+"...";
        }
        keyword2.setValue(value);
        m.put("keyword2", keyword2);
        wxMssVo.setData(m);

        //车牌号码
        TemplateData keyword3 = new TemplateData();
        keyword3.setValue(userCarNumber);
        m.put("keyword3", keyword3);
        wxMssVo.setData(m);


        //温馨提示
        StringBuffer wenxinSb = new StringBuffer();
        wenxinSb.append("本地车提示："+(trafficControlBeanVO.getLocalRemarks()==null?"无":trafficControlBeanVO.getLocalRemarks())+" ");
        wenxinSb.append("外地车提示："+(trafficControlBeanVO.getForeignRemarks()==null?"无":trafficControlBeanVO.getForeignRemarks())+" ");
        wenxinSb.append("全车提示："+trafficControlBeanVO.getAllCarRemarks()==null?"无":trafficControlBeanVO.getAllCarRemarks());
        TemplateData keyword4 = new TemplateData();
        String value4 = wenxinSb.toString();
        if(wenxinSb.toString().length()>60){
            value4 = wenxinSb.toString().substring(0,60)+"...";
        }
        keyword4.setValue(value4);
        m.put("keyword4", keyword4);
        wxMssVo.setData(m);


        //备注
        TemplateData keyword5 = new TemplateData();
        keyword5.setValue("进入小程序查看，图文更清晰");

        m.put("keyword5", keyword5);
        wxMssVo.setData(m);


        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        log.info("小程序推送结果={}", responseEntity.getBody());

        return responseEntity.getBody();


        /*List<TcControlCitys> citys = trafficControlService.getTrafficControlCitys();*/

        /*String cityNameArg = "";*/
        /*
            for (TcControlCitys city : citys) {
                if (city.getCityName().equals(noticeCity)) {
                 cityNameArg = city.getCode();
            }
        }*/


        /*TrafficControlBean trafficControlBean = new TrafficControlBean();
        TrafficControlBeanVO trafficControlBeanVO = new TrafficControlBeanVO();
        List<String> weihaoList =  new ArrayList<>();

        LuBangXianingInfoVO xianxing = LuBangXianxingUtil.getCityXianxingInfo(cityNameArg);
        if(xianxing.getForeigncar().size()!=0){
            LuBangXianingInfoVO.ForeigncarBean localcarBean = xianxing.getForeigncar().get(0);

            String[] xianxingInfos = localcarBean.getNumber().split(";");

            trafficControlBean.setCity(xianxing.getCityname());
            trafficControlBean.setDate(localcarBean.getDate());
            trafficControlBean.setWeek(localcarBean.getWeek());
            trafficControlBean.setCityname(localcarBean.getArea());
            trafficControlBean.setFine("");
            trafficControlBean.setRemarks(localcarBean.getSummary());
            if(noticeType==0){
                trafficControlBean.setIsxianxing(xianxingInfos[0].equals("不限行")==true?0:1);
            }else if(noticeType==1){
                trafficControlBean.setIsxianxing(xianxingInfos[1].equals("不限行")==true?0:1);
            }
            trafficControlBean.setHoliday(localcarBean.getHoliday());
            TrafficControlBean.DesBean desBean = new TrafficControlBean.DesBean();
            desBean.setInfo(localcarBean.getDetail());
            desBean.setTime(localcarBean.getDate());
            desBean.setPlace(localcarBean.getArea());
            trafficControlBean.setDes(Lists.newArrayList(desBean));
            weihaoList.clear();
            if(noticeType==0){
                if(!xianxingInfos[0].equals("不限行")&&!xianxingInfos[0].equals("所有号牌")){
                    String[] weihao = xianxingInfos[0].split(",");
                    for(int count = 0 ;count<weihao.length;count++){
                        if(isNumeric(weihao[count]) ){
                            weihaoList.add(weihao[count]);
                        }
                    }
                    if(!isNumeric(xianxingInfos[0])&&weihaoList.size()==0){
                        weihaoList.add(xianxingInfos[0]);
                    }
                }else if(xianxingInfos[0].equals("所有号牌")){
                    weihaoList.add("-1");
                }
            }else if(noticeType==1){
                if(!xianxingInfos[0].equals("不限行")&&!xianxingInfos[0].equals("所有号牌")){
                    String[] weihao = xianxingInfos[0].split(",");
                    for(int count = 0 ;count<weihao.length;count++){
                        if(isNumeric(weihao[count]) ){
                            weihaoList.add(weihao[count]);
                        }
                    }
                    if(!isNumeric(xianxingInfos[0])&&weihaoList.size()==0){
                        weihaoList.add(xianxingInfos[0]);
                    }
                }else if(xianxingInfos[0].equals("所有号牌")){
                    weihaoList.add("-1");
                }
            }


            trafficControlBeanVO.setForeign("1");
        }

        if(xianxing.getLocalcar().size()!=0){
            LuBangXianingInfoVO.LocalcarBean localcarBean = xianxing.getLocalcar().get(0);

            String[] xianxingInfos = localcarBean.getNumber().split(";");


            trafficControlBean.setCity(xianxing.getCityname());
            trafficControlBean.setDate(localcarBean.getDate());
            trafficControlBean.setWeek(localcarBean.getWeek());
            trafficControlBean.setCityname(localcarBean.getArea());
            trafficControlBean.setFine("");
            trafficControlBean.setRemarks(localcarBean.getSummary());
            if(noticeType==0){
                trafficControlBean.setIsxianxing(xianxingInfos[0].equals("不限行")==true?0:1);
            }else if(noticeType==1){
                trafficControlBean.setIsxianxing(xianxingInfos[1].equals("不限行")==true?0:1);
            }
            trafficControlBean.setHoliday(localcarBean.getHoliday());
            TrafficControlBean.DesBean desBean = new TrafficControlBean.DesBean();
            desBean.setInfo(localcarBean.getDetail());
            desBean.setTime(localcarBean.getDate());
            desBean.setPlace(localcarBean.getArea());
            trafficControlBean.setDes(Lists.newArrayList(desBean));
            weihaoList.clear();
            if(noticeType==0){
                if(!xianxingInfos[0].equals("不限行")&&!xianxingInfos[0].equals("所有号牌")){
                    String[] weihao = xianxingInfos[0].split(",");
                    for(int count = 0 ;count<weihao.length;count++){
                        if(isNumeric(weihao[count]) ){
                            weihaoList.add(weihao[count]);
                        }
                    }
                    if(!isNumeric(xianxingInfos[0])&&weihaoList.size()==0){
                        weihaoList.add(xianxingInfos[0]);
                    }
                }else if(xianxingInfos[0].equals("所有号牌")){
                    weihaoList.add("-1");
                }
            }else if(noticeType==1){
                if(!xianxingInfos[0].equals("不限行")&&!xianxingInfos[0].equals("所有号牌")){
                    String[] weihao = xianxingInfos[0].split(",");
                    for(int count = 0 ;count<weihao.length;count++){
                        if(isNumeric(weihao[count]) ){
                            weihaoList.add(weihao[count]);
                        }
                    }
                    if(!isNumeric(xianxingInfos[0])&&weihaoList.size()==0){
                        weihaoList.add(xianxingInfos[0]);
                    }
                }else if(xianxingInfos[0].equals("所有号牌")){
                    weihaoList.add("-1");
                }
            }

            trafficControlBeanVO.setForeign("0");
        }
        if(xianxing.getAllcars().size()!=0){
            LuBangXianingInfoVO.AllCarBean localcarBean = xianxing.getAllcars().get(0);

            String[] xianxingInfos = localcarBean.getNumber().split(";");


            trafficControlBean.setCity(xianxing.getCityname());
            trafficControlBean.setDate(localcarBean.getDate());
            trafficControlBean.setWeek(localcarBean.getWeek());
            trafficControlBean.setCityname(localcarBean.getArea());
            trafficControlBean.setFine("");
            trafficControlBean.setRemarks(localcarBean.getSummary());
            if(noticeType==0){
                trafficControlBean.setIsxianxing(xianxingInfos[0].equals("不限行")==true?0:1);
            }else if(noticeType==1){
                trafficControlBean.setIsxianxing(xianxingInfos[1].equals("不限行")==true?0:1);
            }
            trafficControlBean.setHoliday(localcarBean.getHoliday());
            TrafficControlBean.DesBean desBean = new TrafficControlBean.DesBean();
            desBean.setInfo(localcarBean.getDetail());
            desBean.setTime(localcarBean.getDate());
            desBean.setPlace(localcarBean.getArea());
            trafficControlBean.setDes(Lists.newArrayList(desBean));
            weihaoList.clear();
            if(noticeType==0){
                if(!xianxingInfos[0].equals("不限行")&&!xianxingInfos[0].equals("所有号牌")){
                    String[] weihao = xianxingInfos[0].split(",");
                    for(int count = 0 ;count<weihao.length;count++){
                        if(isNumeric(weihao[count]) ){
                            weihaoList.add(weihao[count]);
                        }
                    }
                    if(!isNumeric(xianxingInfos[0])&&weihaoList.size()==0){
                        weihaoList.add(xianxingInfos[0]);
                    }
                }else if(xianxingInfos[0].equals("所有号牌")){
                    weihaoList.add("-1");
                }
            }else if(noticeType==1){
                if(!xianxingInfos[0].equals("不限行")&&!xianxingInfos[0].equals("所有号牌")){
                    String[] weihao = xianxingInfos[0].split(",");
                    for(int count = 0 ;count<weihao.length;count++){
                        if(isNumeric(weihao[count]) ){
                            weihaoList.add(weihao[count]);
                        }
                    }
                    if(!isNumeric(xianxingInfos[0])&&weihaoList.size()==0){
                        weihaoList.add(xianxingInfos[0]);
                    }
                }else if(xianxingInfos[0].equals("所有号牌")){
                    weihaoList.add("-1");
                }
            }

            trafficControlBeanVO.setForeign("2");
        }

        if(!trafficControlBean.getCity().isEmpty()){
            BeanUtils.copyProperties(trafficControlBean,trafficControlBeanVO);
        }else{
            trafficControlBeanVO = null;
        }


        BeanUtils.copyProperties(trafficControlBean,trafficControlBeanVO);
*/




/*        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户openid
        wxMssVo.setTemplate_id("znVpnHHBDrDL0DBFU8H_gGqwP3g0LKDiG-TliMf5YMg");
//        wxMssVo.setTemplate_id("3-e2LnDj27x2nvT6MzmfsGN022gXEnI3ZqA9X8t48nc");//模版id
//        wxMssVo.setTemplate_id("znVpnHHBDrDL0DBFU8H_gJRpmbhxv8SqMHqiVk9JaJY");
        wxMssVo.setForm_id(formid);//formid


        Map<String, TemplateData> m = new HashMap<>(5);

        //城市
        TemplateData keyword1 = new TemplateData();
        keyword1.setValue(noticeCity);
        m.put("keyword1", keyword1);

        //限行号码
        TemplateData keyword2 = new TemplateData();
        List<Integer> xxweihao = trafficControlBean.getXxweihao();
        String weihao = "";
        for (Integer wh : xxweihao){
            weihao += String.valueOf(wh) + " ";
        }
        keyword2.setValue(weihao);
        m.put("keyword2", keyword2);
        wxMssVo.setData(m);


        //车牌号码
        TemplateData keyword3 = new TemplateData();
        keyword3.setValue(userCarNumber);
        m.put("keyword3", keyword3);
        wxMssVo.setData(m);



*//*        //是否限行
        TemplateData keyword2 = new TemplateData();
        keyword2.setValue(trafficControlBean.getIsxianxing()==1?"是":"否");
        m.put("keyword2", keyword2);
        wxMssVo.setData(m);*//*

*//*        //日期
        TemplateData keyword3 = new TemplateData();
        keyword3.setValue(trafficControlBean.getDate());
        m.put("keyword3", keyword3);
        wxMssVo.setData(m);
 *//*
        //温馨提示
        TemplateData keyword4 = new TemplateData();
        *//*keyword4.setValue(userCarNumber);*//*
        m.put("keyword4", keyword4);
        wxMssVo.setData(m);

        //备注
        TemplateData keyword5 = new TemplateData();
        keyword5.setValue(trafficControlBean.getRemarks());
        m.put("keyword5", keyword5);
        wxMssVo.setData(m);



        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        log.info("小程序推送结果={}", responseEntity.getBody());
        return responseEntity.getBody();*/
    }

    /*
     * 获取access_token
     * appid和appsecret到小程序后台获取，当然也可以让小程序开发人员给你传过来
     * */
    public  String getAccess_token(String appid, String appsecret) {
        RestTemplate restTemplate = new RestTemplate();
        //获取access_token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appid + "&secret=" + appsecret;
        String json = restTemplate.getForObject(url, String.class);
        AccessToken accessToken = JSONObject.parseObject(json, AccessToken.class);
        return accessToken.getAccess_token();
    }


    public static void main(String[] args) {
        WxPushServiceQcl sq = new WxPushServiceQcl();
        sq.pushOneUser("杭州市","oscv15aZ_m1vqiw2Rz5rG1sIcVGg","462eed7efb1e40dfb4fd8063db806eab",0,"浙A123456");

        //二维码生成
       /* RestTemplate restTemplate = new RestTemplate();
        //获取access_token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + getOpenIdutil.appid + "&secret=" + getOpenIdutil.secret;
        String json = restTemplate.getForObject(url, String.class);
        AccessToken accessToken = JSONObject.parseObject(json, AccessToken.class);
        String access_token = accessToken.getAccess_token();

        String Url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
        Map<String,String> map = new HashMap<>();
        map.put("scene","123asd");
        String result = null;
        try {
            result = HttpClientUtils.getInstance().sendPostDataByJson(Url, JsonUtils.toJSONString(map),"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(result);*/

    }


    /**
     * 截取尾号
     * @param number
     * @return
     */
    private List<String> getXxWeihao(String number,int num){
        String[] split = number.split(";");
        List<String> resultList = new ArrayList<>(2);
        String[] weihao = null;
        if("不限行".equals(split[num])){
            weihao = new String[]{"-1"};   //不限行
        }else if("所有号牌".equals(split[num])){
            weihao = new String[]{"-2"};   //所有车牌
        }else{
            weihao = split[num].split(",");   //进行分割
        }
        Collections.addAll(resultList,weihao);
        return resultList;
    }

    /*
     * @author : zhangHaiWen
     * @date   : 2019/3/8 1:55
     * @desc   :    拼接字符串
     * @param  :  * @param null
     * @return :
    */
    private String getMsgInfo(List<String> list){
        if(list!=null && list.size()>0){
            // -1:不限行      -2：所有车牌
            if(list.size()==1){
                if(list.get(0).equals("-1")){
                    return "不限行";
                }else if(list.get(0).equals("-2")){
                    return "所有车牌";
                }
            }else if(list.size()>1){
                return list.get(0)+","+list.get(1);
            }
        }

        return "";
    }


}